<template>
  <div class="view">
    <span class="view-title">新建围栏</span>
    <el-button @click="router.push('/geofenceMap')" class="title-right-button" type="primary">新建围栏</el-button>
  </div>
  <!--第6步:创建地图容器元素-->
  <div id="mapContainer" style="width: 100%;height: 84vh;"></div>
  <!--新增电子围栏弹窗-->
  <el-dialog title="围栏信息" v-model="dialogVisible">
    <el-form label-width="80px">
      <el-form-item label="围栏名称">
        <el-input placeholder="请输入围栏名称" v-model="geofence.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="saveGeofence">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {DrawScene, DrawControl, OperateEventType} from 'bmap-draw';
import router from "@/router";
import {nextTick, onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import axios from "axios";

// 定义变量控制弹窗是否出现
const dialogVisible = ref(false);
//关闭弹窗
const closeDialog = () => {
  ElMessageBox.confirm(
      '确定关闭吗?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        //关闭弹窗
        dialogVisible.value = false;
        //清空不用的围栏遮盖物
        map.clearOverlays();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}

//定义保存围栏的方法
const saveGeofence = () => {
  if (!geofence.value.name || geofence.value.name.trim().length == 0) {
    ElMessage.error('围栏名称不能为空!');
    return;
  }
  //因为围栏位置信息position是一个对象,所以需要先转为字符串
  geofence.value.position = JSON.stringify(geofence.value.position);
  //继续处理geofence,转为qs字符串给后端发新增请求
  let data = qs.stringify(geofence.value);
  console.log(data);
  //给后端发新增围栏的请求
  axios.post(BASE_URL + '/v1/geofence/save', data)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('保存成功!');
          //关闭弹窗
          dialogVisible.value = false;
          //跳转至电子围栏管理页面
          router.push('/geofence');
        } else {
          ElMessage.error(response.data.msg);
        }
      });
}
//准备对象用来存储围栏的信息
const geofence = ref({
  name: '', // 围栏名称
  position: {} // 围栏信息
})
//定义全局变量用于保存地图对象
var map;
onMounted(() => {
  // todo 接收参数
  // todo const fence = route.query.fenceData;
  // todo alert(fence);
  //表示在DOM更新之后再执行,因为我们要确保上方div创建之后再给div里渲染地图
  nextTick(() => {
    //第7步:创建地图示例,注意:不要引入,忽略提示!
    map = new BMapGL.Map("mapContainer");
    //第8步:设置中心点坐标，设置经纬度104.066541, 30.572269
    let point = new BMapGL.Point(104.066541, 30.572269);
    //第9步：设置地图显示的中心点与地图缩放级别
    map.centerAndZoom(point, 15);
    //鼠标滚轮缩放比例
    map.enableScrollWheelZoom();

    //添加地图绘制控件
    //1.创建绘制场景类,这是其他绘制控件使用的基类,注意:DrawScene需要导入!
    const scene = new DrawScene(map);
    //2.创建绘制控件类,并将上一回创建好的绘制场景作为构造参数传入,注意:DrawControl也需要导入!
    const drawContrl = new DrawControl(scene, {
      //3.绘制控件配置项:
      //3.1不显示对应图标的用途提示
      enableTips: false,
      //3.2 设置绘制控件的显示位置(右上角)
      anchor: BMAP_ANCHOR_TOP_RIGHT,
      //3.3 设置绘制控件显示哪些绘制项 circle圆形 rectangle矩形
      drawingItems: [
        'circle',
        'rectangle'
      ]
    });

    //添加一个监听事件,监听绘制完成事件(点击对钩事件)
    scene.addEventListener(OperateEventType.COMPLETE, (event) => {
      dialogVisible.value = true;
      let overlay = event.target.overlay;
      if (overlay instanceof BMapGL.Circle) {
        //设置围栏类型为圆形
        geofence.value.position.type = 'circle';
        //设置围栏半径
        geofence.value.position.radius = overlay.getRadius();
        //设置圆心的经度和纬度
        geofence.value.position.latitude = overlay.getCenter().lat;
        geofence.value.position.longitude = overlay.getCenter().lng;
        console.log(geofence.value);
        console.log(geofence.value.position);
      } else {
        let recPoints = [];
        for (let i = 0; i < 4; i++) {
          recPoints.push(overlay.points[i].latLng.lng + '-' + overlay.points[i].latLng.lat);
        }
        //设置围栏类型为矩形
        geofence.value.position.type = 'rectangle';
        //设置围栏的顶点坐标字符串
        geofence.value.position.points = recPoints.join(',');
        console.log(geofence.value);
        console.log(geofence.value.position);
      }
    });

    //4.将绘制控件添加到地图上
    map.addControl(drawContrl);
  })
})


</script>

<style scoped>
.view {
  height: 4vh;
  padding: 5px 20px;
  background-color: #fff;
}

.view-title {
  line-height: 40px;
  font-size: 20px;
  font-weight: bold;
}

.title-right-button {
  float: right;
  margin-top: -3px;
}
</style>